package com.irdstudio.efp.esb.api.rest.hj;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.efp.esb.api.bean.hj.ReqBdLoanCompensationStatementBean;
import com.irdstudio.efp.esb.api.bean.hj.RespBdLoanCompensationStatementBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.loan.service.facade.LoanCompensationStatementServiceV2;

/**
 * 
 * TODO 百度代偿处理结果推送接口
 * 
 * @author wanglihua
 * @since 2019年4月3日 下午7:27:57
 * @version 1.0
 */
@RestController
@RequestMapping("/esb")
public class BdLoanCompensationStatementController {

	private static Logger logger = LoggerFactory.getLogger(BdLoanCompensationStatementController.class);

	@ModelAttribute("esbReqServiceBean")
	public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
		logger.info("获取ESB请求对象，校验 ESB请求系统头和请求应用头对象开始");
		EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
		return esbReqServiceBean;
	}

	@ModelAttribute("reqBdLoanCompensationStatementBean")
	public ReqBdLoanCompensationStatementBean getReqEsbBodyBean(HttpServletRequest request) {
		logger.info("获取百度代偿处理结果推送接口请求对象，校验百度代偿处理结果推送接口请求体对象开始");
		String esbReqBody = (String) request.getAttribute("esbReqBody");
		return JSONObject.parseObject(esbReqBody, ReqBdLoanCompensationStatementBean.class);
	}

	@PostMapping("/SERVICE_30220012_01")
	public EsbRespServiceBean doRecv(
			@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
			@Validated @ModelAttribute("reqBdLoanCompensationStatementBean") ReqBdLoanCompensationStatementBean reqBdLoanCompensationStatementBean,
			BindingResult br2, Exception exception) throws Exception {
		
		String curDate = reqBdLoanCompensationStatementBean.getBaiduAcctDt();
		String retCode = reqBdLoanCompensationStatementBean.getRetCd();
		String retMsg = reqBdLoanCompensationStatementBean.getRetMsg();
		String channelNo = reqBdLoanCompensationStatementBean.getChanFlg();
		logger.info("**********************百度代偿处理结果推送接口开始，" + "获取到的时间为："+"\"" + curDate +"\""+ "，获取到的码值为：" +"\""+ retCode +"\""+"，获取到的信息为："+"\""+ retMsg+"\""+"**********************");
		try {
			// 1.通过切面校验进件申请参数是否正确，如不正确则返回错误信息
			if (Objects.nonNull(exception)) {
				throw exception;
			}
			String successFlag = BaseConstant.COMPENSATION_STS_03;
			String failFlag = BaseConstant.COMPENSATION_STS_02;
			
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");//百度账务日期
			
			try {
				format.parse(curDate);
			} catch (Exception e) {
				return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
						JSON.toJSONString(
								buildRespBdLoanComStsBean(EsbBizEnums.RetCodeEnum.FAILURE.getVALUE(), "百度账务日期格式[yyyy-MM-dd]不正确，请检查！")),
						EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), EsbBizEnums.RetCodeEnum.FAILURE.getVALUE(),
						"百度账务日期格式[yyyy-MM-dd]不正确，请检查！");
			}
			
			if(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE().equals(retCode) && !"".equals(curDate) && curDate != null) {
				int flag = loanCompensationStatementServiceV2.timeUpdateLoanCompensationStatement(curDate,successFlag);
				if (flag == -1) {
					logger.info("**********************修改代偿状态失败！**********************");
					throw new Exception("修改数据表异常!");
				} else {
					logger.info("**********************修改代偿状态成功！修改代偿状态为代偿成功（compensation_sts = 03）**********************");
					return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
							JSON.toJSONString(buildRespBdLoanComStsBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),EsbBizEnums.RetCodeMsg.SUCCESS_MSG.VALUE)),
							EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),EsbBizEnums.RetCodeMsg.SUCCESS_MSG.VALUE);
				}
			} else {
				int flag = loanCompensationStatementServiceV2.timeUpdateLoanCompensationStatement(curDate,failFlag);
				if (flag == -1) {
					logger.info("**********************修改代偿状态失败！**********************");
					throw new Exception("修改数据表异常!");
				} else {
					logger.info("**********************修改代偿状态成功！修改代偿状态为代偿失败（compensation_sts = 02）**********************");
					return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
							JSON.toJSONString(buildRespBdLoanComStsBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),EsbBizEnums.RetCodeMsg.SUCCESS_MSG.VALUE)),
							EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),EsbBizEnums.RetCodeMsg.SUCCESS_MSG.VALUE);
				}
			}
		} catch (ESBException e) {
			logger.error("**********************百度代偿处理结果推送接口处理失败!**********************" + e.getMessage());
			e.printStackTrace();
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
					buildRespBdLoanComStsBean(EsbBizEnums.RetCodeEnum.FAILURE.getVALUE(), e.getMessage()).toString(), //
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
					EsbBizEnums.RetCodeEnum.FAILURE.getVALUE(), //
					e.getMessage());
		} catch (Exception e) {
			logger.error("**********************百度代偿处理结果推送接口处理失败!**********************" + e.getMessage());
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
					JSON.toJSONString(buildRespBdLoanComStsBean(EsbBizEnums.RetCodeEnum.FAILURE.getVALUE(), e.getMessage())), //
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
					EsbBizEnums.RetCodeEnum.FAILURE.getVALUE(), //
					e.getMessage());
		} finally {
			logger.info("**********************获取百度代偿处理结果推送接口请求处理结束！**********************");
		}
	}
	
	private Object buildRespBdLoanComStsBean(String retCode, String retMsg) {
		logger.info("**********************获取百度代偿处理结果推送接口请求处理结果报文组装开始！**********************");
		RespBdLoanCompensationStatementBean respBdLoanCompensationStatementBean = new RespBdLoanCompensationStatementBean();
		respBdLoanCompensationStatementBean.setRetCode(retCode);
		respBdLoanCompensationStatementBean.setRetMsg(retMsg);
		logger.info("**********************获取百度代偿处理结果推送接口请求处理结果报文组装结束！**********************");
		return respBdLoanCompensationStatementBean;
	}

	@Autowired
	@Qualifier("loanCompensationStatementServiceV2")
	private LoanCompensationStatementServiceV2 loanCompensationStatementServiceV2;
}
